package model

import (
	"github.com/jinzhu/gorm"
	"log"
	. "pdpconv/database"
)

const (
	TRANS_INIT = iota
	TRANS_ING
	TRANS_END
)

func init(){
	//DB.DropTable(&Document{})
	//DB.DropTable(&Image{})
	if !DB.HasTable(&Document{}) {
		DB.CreateTable(&Document{})
	}
	if !DB.HasTable(&Image{}) {
		DB.CreateTable(&Image{})
	}
}

type Document struct {
	gorm.Model
	Name string `form:"name" json:"name" gorm:"not null"`
	Size int `json:"size"`
	PageSize int `json:"pageSize"`
	FilePath string `form:"FilePath" json:"filePath" gorm:"not null"`
	FileSuffix string `json:"fileSuffix"`
	Tag string `form:"tag" json:"tag"`  //标识
	Status int `json:"status"`
	FileId int64 `json:"fileId" gorm:"not null"`

	Images []*Image `json:"images" gorm:"ForeignKey:DocId"`
}

type Image struct {
	gorm.Model
	Name string `json:"name" gorm:"not null"`
	PageNum int `json:"pageNum" gorm:"not null"`
	Size int `json:"size"`
	FilePath string `json:"filePath" gorm:"not null"`
	FileSuffix string `json:"fileSuffix"`
	FileId int64 `json:"fileId" gorm:"not null"`
	DocId uint `json:"docId" gorm:"index:index_doc"`
}

/**
保存文档
 */
func SaveDoc(doc *Document) error{
	tx := DB.Begin()
	if err := tx.Create(doc).Error;err != nil{
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// 更新文档转换状态
func UpdateDocStatusAndPageSize(id uint,status,pageSize int) error{
	tx := DB.Begin()
	if err := tx.Model(&Document{}).Updates(Document{Status:status,PageSize:pageSize}).Where("id",id).Error;err != nil{
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// 通过id查找文档
func SelectDocById(id uint,result *Document) error{
	return DB.First(result,id).Error
}

//通过标签查找文档
func SelectDocsByTag(tag string,result *[]Document) error {
	return DB.Where("tag=?",tag).Find(result).Error
}

// 分页查找文档
func FindPageList(condition Document,pageNum int,pageSize int,result *[]Document) error {

	return DB.Where(&condition).Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(result).Error
}

// 保存图片
func SaveImages(images []*Image) error{
	tx := DB.Begin()
	log.Print(images)
	for image := range images {
		if err := tx.Create(&image).Error;err != nil{
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

// 保存图片
func SaveImage(image *Image) error{
	tx := DB.Begin()
	if err := tx.Create(image).Error;err != nil{
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func GetImage(imageId int,image *Image) error{
	return DB.First(image).Where("id",imageId).Error
}

func GetImageByFileId(fileId int64,image *Image) error{
	return DB.First(image).Where("file_id",fileId).Error
}

// 通过docId查找图片
func FindImages(id uint,images *[]Image) error {
	return DB.Where("doc_id",id).Order("created_at",true).Find(images).Error
}
